package com.proxy.server.backend.nio.adapter;

import com.proxy.common.packet.BinaryPacket;
import com.proxy.common.utils.MySqlByteBufUtil;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

import java.util.List;

/**
 * Created by liufish on 16/7/14.
 */
public class BackendPacketDecoder extends ByteToMessageDecoder {


    int  count;

    /**
     * mysql 传输协议头长度
     */
    private final int HEADER_SIZE = 4;


    private final int LENGTH_SIZE = 3;

    /**
     *
     * mysql 最大支持16M数据的传输
     */
    private final int MAX_SIZE = 16 * 1024 * 1024;



    /**
     *  mysql传输协议 length + id + body,其中length不包括 本身和id，只代表body的长度。
     */
    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> list) throws Exception {



        if (byteBuf.readableBytes() < HEADER_SIZE) {
            return;
        }


        int length = MySqlByteBufUtil.read3(byteBuf);
        if (length > MAX_SIZE ) {
            byteBuf.resetReaderIndex();
            throw new IllegalArgumentException("Packet size over the limit " + MAX_SIZE);
        }
        if( length < 0){
            byteBuf.resetReaderIndex();
            throw new IllegalArgumentException("Packet size less than zero ");
        }

        byte id = byteBuf.readByte();
        if (byteBuf.readableBytes() < length) {
            byteBuf.resetReaderIndex();
            return;
        }
        byte [] body = byteBuf.readBytes(length).array();

        BinaryPacket packet = new BinaryPacket(length,id,body);
        list.add(packet);
        count ++;
        if(count > 1000){
            return;
        }
        System.out.println("********");
    }
}
